package edu.neu.springcloud.controller;

import edu.neu.springcloud.entity.Commodity;
import edu.neu.springcloud.entity.CommodityVo;
import edu.neu.springcloud.entity.Factory;
import edu.neu.springcloud.service.CommodityClientService;
import edu.neu.springcloud.service.FactoryClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class CommodityConsumerController {
    @Autowired
    private CommodityClientService commodityClientService;

    @Autowired
    private FactoryClientService factoryClientService;

    @GetMapping("/list")
    public List<CommodityVo> list(@RequestParam(value = "id", required = false) Long id,
                                  @RequestParam(value = "fac_id", required = false) Long fac_id,
                                  @RequestParam(value = "name", required = false) String name,
                                  @RequestParam(value = "price", required = false) Float price) {
        List<Commodity> commodityList = commodityClientService.getAll(id, fac_id, name, price);
        List<CommodityVo> result = new ArrayList<>();
        for (Commodity c : commodityList) {
            // 调用factory微服务，获取这个商品的factory信息，最后形成CommodityVo对象
            List<Factory> factoryList =  factoryClientService.getAll(c.getFac_id(), null);
            if (factoryList.isEmpty() == false && factoryList.size() == 1){
                result.add(new CommodityVo(c, factoryList.get(0).getName()));
            }
        }
        return result;
    }

    @PostMapping("/add")
    public boolean add(@RequestBody Commodity commodity) {
        return commodityClientService.add(commodity);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Commodity commodity) {
        Random random = new Random();
        Commodity c = commodityClientService.getAll(1L,null,null,null).get(0).setName("modify"+ random.nextInt());
        System.out.println(c);
        return commodityClientService.update(commodity);
    }

    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id")Long id) {
        return commodityClientService.delete(id);
    }

}
